<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建自定义字段" : "编辑自定义字段" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form
      class="pl30 pr30"
      :model="formData"
      ref="form"
      label-position="top"
    >
      <el-form-item label="所属子表">
        <!-- <el-select
          :disabled="!isNew"
          v-model="formData.parentId"
          placeholder="请选择所属子表"
          style="width: 100%"
          clearable
          @change="onChange"
        >
          <el-option
            :value="i.id"
            :label="i.name"
            v-for="(i, index) in subTableList"
            :key="index + '_' + i.id"
          >
          </el-option>
        </el-select> -->
        <tree-select
          @change="onChange"
          :disabled="!isNew"
          style="width: 100%"
          v-model="formData.parentId"
          :treeData="subTableTreeData"
          :fieldMap="fieldMap"
        />
      </el-form-item>
      <el-form-item
        label="字段编码"
        prop="code"
        :rules="[
          { required: true, message: '字段编码不能为空', trigger: 'change' },
          {
            pattern: COMMON_CODE_REG_64,
            message: '请输入有效的字段编码',
            trigger: 'change',
          },
          { validator: codeValidator, trigger: 'change' },
        ]"
      >
        <template slot="label"
          >字段编码
          <el-tooltip
            popper-class="custom-popper"
            :content="COMMON_CODE_REG_64_MSG"
            placement="top"
          >
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <el-input
          :disabled="!isNew"
          v-model.trim="formData.code"
          placeholder="请输入字段编码"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item
        label="字段名称"
        prop="name"
        :rules="[
          { required: true, message: '字段名称不能为空', trigger: 'change' },
          { validator: nameValidator, trigger: 'change' },
        ]"
      >
        <el-input
          v-model.trim="formData.name"
          placeholder="请输入字段名称"
          :maxlength="64"
          show-word-limit
        >
        </el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="handleCancel">{{ $t("sys.cancel") }}</el-button>
      <el-button type="primary" @click="submit">{{
        $t("sys.confirm")
      }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { SYSTEM_FIELD } from "@/utils/const"
import { COMMON_CODE_REG_64, COMMON_CODE_REG_64_MSG } from "@/utils/reg"
import { uuid } from "@/utils/common.js"
import { cloneDeep } from "lodash"
import { getTreeNodeById } from "@/utils/util.js"
export default {
  props: {
    fieldList: {
      type: Array,
      default: () => {
        return []
      },
    },
    subTableTreeData: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    return {
      COMMON_CODE_REG_64,
      COMMON_CODE_REG_64_MSG,
      showVisible: false,
      formData: {
        id: "",
        parentId: "",
        parentCode: "",
        code: "",
        name: "",
      },
      selectSubTable: {},
      fieldMap: {
        children: "children",
        label: "ExpressionName",
      },
    }
  },
  computed: {
    isNew() {
      return !this.formData.id
    },
    subTableList() {
      return this.fieldList.filter((i) => i.type === "SUB_TABLE") || []
    },
  },
  methods: {
    add() {
      this.showVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    edit(data) {
      this.formData = cloneDeep(data)
      // this.selectSubTable = data.parentId
      //   ? this.subTableList.filter((i) => i.id === data.parentId)[0]
      //   : {}
      this.selectSubTable = getTreeNodeById(
        this.fieldList,
        data.parentId,
        "children"
      )
      console.log(this.selectSubTable, "selectSubTable")
      this.showVisible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    //校验code
    codeValidator(rule, value, callback) {
      if (SYSTEM_FIELD.includes(value)) {
        callback(new Error("系统字段不可用"))
      } else if (this.formData.parentId) {
        if (
          this.selectSubTable &&
          this.selectSubTable.children
            .filter((i) => i.id !== this.formData.id)
            .find((i) => i.code === value)
        ) {
          callback(new Error("字段编码已存在"))
        } else {
          callback()
        }
      } else if (
        this.fieldList
          .filter((i) => i.id !== this.formData.id)
          .find((i) => i.code === value)
      ) {
        callback(new Error("字段编码已存在"))
      } else {
        callback()
      }
    },
    //校验name
    nameValidator(rule, value, callback) {
      if (this.formData.parentId) {
        if (
          this.selectSubTable &&
          this.selectSubTable.children
            .filter((i) => i.id !== this.formData.id)
            .find((i) => i.name === value)
        ) {
          callback(new Error("字段名称已存在"))
        } else {
          callback()
        }
      } else if (
        this.fieldList
          .filter((i) => i.id !== this.formData.id)
          .find((i) => i.name === value)
      ) {
        callback(new Error("字段名称已存在"))
      } else {
        callback()
      }
    },
    //切换子表
    onChange(v) {
      this.selectSubTable = getTreeNodeById(this.fieldList, v, "children") || {}
      this.$set(this.formData, "parentCode", this.selectSubTable.code)
      this.$refs.form.validateField(["code", "name"])
    },
    //保存数据
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { id, parentId, parentCode, code, name } = this.formData
          let fieldData = {
            isCustom: true,
            id: id || uuid(6),
            parentId,
            parentCode,
            code,
            name,
          }
          this.$emit("ok", { fieldData, isNew: this.isNew })
          this.handleCancel()
        }
      })
    },
    //关闭弹窗
    handleCancel() {
      this.showVisible = false
      this.formData = {
        id: "",
        parentId: "",
        parentCode: "",
        code: "",
        name: "",
      }
    },
  },
}
</script>
